package com.car.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.car.configtion.AlipayConfig;
import com.car.entity.Order;
import com.car.service.order.OrderServiceImpl;
import com.car.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

@RestController
public class AlipayControl {

    private String Sstart="<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
            "<html>\n" +
            "<head>\n" +
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
            "<title>退款</title>\n" +
            "</head>\n" +
            "<%@ page language=\"java\" contentType=\"text/html; charset=utf-8\" pageEncoding=\"utf-8\"%>\n" +
            "<%@ page import=\"com.alipay.config.*\"%>\n" +
            "<%@ page import=\"com.alipay.api.*\"%>\n" +
            "<%@ page import=\"com.alipay.api.request.*\"%>";

    private String Send="<body>\n" +
            "</body>\n" +
            "</html>";

    @ResponseBody
    @RequestMapping("/alipayorder")
    public String ali(String WIDout_trade_no,String WIDtotal_amount,String WIDsubject,String WIDbody) throws UnsupportedEncodingException, AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(WIDout_trade_no.getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(WIDtotal_amount.getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(WIDsubject.getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(WIDbody.getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return Sstart+result+Send;

    }

    @ResponseBody
    @RequestMapping("/ZhiFuZJ")
    public String ZhiFuZJ(String WIDout_trade_no,String WIDtotal_amount,String WIDsubject,String WIDbody) throws UnsupportedEncodingException, AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url+"/ZJPriceYes");
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url+"/ZJPriceYes");

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(WIDout_trade_no.getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(WIDtotal_amount.getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(WIDsubject);
        //商品描述，可空
        String body = new String(WIDbody);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return Sstart+result+Send;

        /**
         * <form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=Ra996mSFbxTpPdFIG4gyUA9nHQIHx3uaZboa1qoqrP9nldGuCTAU8C0VpxjmDJZxsw%2BoiY0GGoMYVvltKscE74n%2BPi6%2BK%2F7yIEsMUOZwcx%2Bvv7qcLRnx19s2vjJMCWB8CganwRqseaUAmOM4buBtYigbDSyb47CIvjmh9j6DlRhkipMb02dd5klwHn4gGdqiK%2F2TpSiAuQOewpJPwhKEkt4zSIzlenwGTNDebUKgJf96gJgw80Dqw0Sm%2B9xsFjTn1Hw%2BfkCfPKijAMlQLdxkVrl3Bp3yEgTv7LYH730Qy5K%2Bxfp5m0Wun6I1BVS9EGjFcEzASlkiTznjxloRc2MvOA%3D%3D&return_url=http%3A%2F%2F4fch66.natappfree.cc%2FZJPriceYes&notify_url=http%3A%2F%2F4fch66.natappfree.cc%2FZJPriceYes&version=1.0&app_id=2021000118661334&sign_type=RSA2&timestamp=2021-12-09+15%3A58%3A06&alipay_sdk=alipay-sdk-java-4.9.79.ALL&format=json">
         * <input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;212434945&quot;,&quot;total_amount&quot;:&quot;880.94&quot;,&quot;subject&quot;:&quot;租车租金&quot;,&quot;body&quot;:&quot;租车租金，不包含违章罚款&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}">
         * <input type="submit" value="立即支付" style="display:none" >
         * </form>
         * <script>document.forms[0].submit();</script>
         */

    }

    @Autowired
    OrderServiceImpl orderServiceImpl;

    @ResponseBody
    @RequestMapping("/ZhiFuYJ")
    public String ZhiFuYJ(String orderId) throws UnsupportedEncodingException, AlipayApiException {

        Order order = orderServiceImpl.selectById(orderId);
        String WIDout_trade_no = order.getOrderId();
        String WIDtotal_amount = String.valueOf(order.getOrderDeposit());
        String WIDsubject = "支付租车订单押金";
        String WIDbody = new Date().toLocaleString()+"：租车押金";

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url+"/YJPriceYes");
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url+"/YJPriceYes");

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(WIDout_trade_no.getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(WIDtotal_amount.getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(WIDsubject);
        //商品描述，可空
        String body = new String(WIDbody);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return Sstart+result+Send;

    }


    @ResponseBody
    @RequestMapping("/TuiHuanYJ")
    public ModelAndView TuiHuanYJ(String orderId,String ReturnPrice,String ReturnReason,String Returnrequest) throws UnsupportedEncodingException, AlipayApiException {
        //
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = new String(orderId.getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String trade_no = new String();
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(ReturnPrice.getBytes("ISO-8859-1"), "UTF-8");
        //退款的原因说明
        String refund_reason = new String(ReturnReason.getBytes("ISO-8859-1"), "UTF-8");
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = new String(Returnrequest.getBytes("ISO-8859-1"), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");

        AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);

        ModelAndView mv =new ModelAndView();
        ResultMsg resultMsg = new ResultMsg();
        String body = response.getBody();
        Map<String,Object> respon = (Map<String, Object>) JSON.parse(body);
        Map<String,Object> map = (Map<String, Object>) respon.get("alipay_trade_refund_response");
        if(map.get("code").equals("10000")){
            System.out.println("调用成功");
            mv.addObject("out_trade_no",map.get("out_trade_no"));
            mv.addObject("refund_fee",map.get("refund_fee"));
            mv.setViewName("redirect:/RZJPriceYes");
            return mv;
        } else {
            resultMsg.setFlag(0);
            resultMsg.setMsg("失败");
            mv.addObject("resultMsg",resultMsg);
            mv.setViewName("result");
            return mv;
        }
    }

    @ResponseBody
    @RequestMapping("/BuZuZJin")
    public String BuZuZJin(String ID,String ReturnPrice,String ReturnReason,String Returnrequest) throws UnsupportedEncodingException, AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url+"/SZJPriceYes");
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url+"/SZJPriceYes");

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(ID.getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(ReturnPrice.getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(ReturnReason);
        //商品描述，可空
        String body = new String(Returnrequest);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return Sstart+result+Send;

        /**
         * <form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=utf-8&method=alipay.trade.page.pay&sign=Ra996mSFbxTpPdFIG4gyUA9nHQIHx3uaZboa1qoqrP9nldGuCTAU8C0VpxjmDJZxsw%2BoiY0GGoMYVvltKscE74n%2BPi6%2BK%2F7yIEsMUOZwcx%2Bvv7qcLRnx19s2vjJMCWB8CganwRqseaUAmOM4buBtYigbDSyb47CIvjmh9j6DlRhkipMb02dd5klwHn4gGdqiK%2F2TpSiAuQOewpJPwhKEkt4zSIzlenwGTNDebUKgJf96gJgw80Dqw0Sm%2B9xsFjTn1Hw%2BfkCfPKijAMlQLdxkVrl3Bp3yEgTv7LYH730Qy5K%2Bxfp5m0Wun6I1BVS9EGjFcEzASlkiTznjxloRc2MvOA%3D%3D&return_url=http%3A%2F%2F4fch66.natappfree.cc%2FZJPriceYes&notify_url=http%3A%2F%2F4fch66.natappfree.cc%2FZJPriceYes&version=1.0&app_id=2021000118661334&sign_type=RSA2&timestamp=2021-12-09+15%3A58%3A06&alipay_sdk=alipay-sdk-java-4.9.79.ALL&format=json">
         * <input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;212434945&quot;,&quot;total_amount&quot;:&quot;880.94&quot;,&quot;subject&quot;:&quot;租车租金&quot;,&quot;body&quot;:&quot;租车租金，不包含违章罚款&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;}">
         * <input type="submit" value="立即支付" style="display:none" >
         * </form>
         * <script>document.forms[0].submit();</script>
         */

    }

    /**
     *
     * @param orderId
     * @param ReturnPrice
     * @param ReturnReason
     * @param Returnrequest
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @ResponseBody
    @RequestMapping("/TuiHuanYJCESHI")
    public String TuiHuanYJCESHI(String orderId,String trade_nos,String ReturnPrice,String ReturnReason,String Returnrequest) throws UnsupportedEncodingException, AlipayApiException {
//获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = new String(orderId.getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        String trade_no = new String(trade_nos.getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = new String(ReturnPrice.getBytes("ISO-8859-1"),"UTF-8");
        //退款的原因说明
        String refund_reason = new String(ReturnReason);
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = new String();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        //输出
        return result;
    }


}
